<?php
/**
 * Created by PhpStorm.
 * User: yandian
 * Date: 16/5/20
 * Time: 15:35
 */

namespace app\common\controller;

use think\Config;
use think\Controller;
use think\Response;

class LiteBase extends Controller
{
    private $_filterQueryData = true;
    private $_unFilterFields = [];

    public function __construct()
    {
        parent::__construct();
        if ($this->_filterQueryData) {
            $this->filterQueryData();
        }
    }


    public function returnJson($data)
    {
        Response::type('json');
        return $data;
    }

    public function jsonSuccess($info = '')
    {
        return $this->returnJson([
            'info' => $info,
            'status' => 1
        ]);
    }

    public function jsonFail($info = '')
    {
        return $this->returnJson([
            'info' => $info,
            'status' => 0
        ]);
    }

    public function commonData($data)
    {
        if (empty($data)) {
            return $this->jsonFail('');
        }
        if (!is_array($data)) {
            return $this->jsonFail($data);
        }
        if (isset($data[0]) && $data[0] == true) {
            return $this->jsonSuccess(isset($data[1]) ? $data[1] : '');
        }
        return $this->jsonFail(isset($data[1]) ? $data[1] : '');
    }

    private function _filterData($item)
    {
        if (is_array($item)) {
            foreach ($item as $k => $vv) {
                $item[$k] = $this->_filterData($vv);
            }
            return $item;
        }
        return htmlspecialchars($item);
    }

    protected function filterQueryData()
    {
        foreach ($_POST as $k => $v) {
            if (in_array($k, $this->_unFilterFields)) {
                continue;
            }
            $_POST[$k] = $this->_filterData($v);
        }
        foreach ($_GET as $k => $v) {
            if (in_array($k, $this->_unFilterFields)) {
                continue;
            }
            $_GET[$k] = $this->_filterData($v);
        }
        foreach ($_REQUEST as $k => $v) {
            if (in_array($k, $this->_unFilterFields)) {
                continue;
            }
            $_REQUEST[$k] = $this->_filterData($v);
        }
    }

    protected function setUnFilterQueryFields(array $fields)
    {
        $this->_unFilterFields = $fields;
    }

    protected function getImageHost()
    {
        return Config::get('oss.OSS_IMAGE_HOST');
    }
}